using System;
using System.Collections.Generic;
using System.Drawing;
using ZXing;
using ZXing.Common;

namespace SoftManager
{
    /// <summary>
    /// 二维码帮助类 - 使用ZXing库生成标准二维码
    /// </summary>
    public static class QrCodeHelper
    {
        /// <summary>
        /// 生成二维码图片 (默认256x256)
        /// </summary>
        /// <param name="content">要编码的文本内容</param>
        /// <returns>二维码图片</returns>
        public static Bitmap GenerateQrCode(string content)
        {
            return GenerateQrCode(content, 256, 256);
        }
        
        /// <summary>
        /// 生成二维码图片
        /// </summary>
        /// <param name="content">要编码的文本内容</param>
        /// <param name="width">图片宽度</param>
        /// <param name="height">图片高度</param>
        /// <returns>二维码图片</returns>
        public static Bitmap GenerateQrCode(string content, int width, int height)
        {
            try
            {
                // 设置二维码编码参数
                var hints = new Dictionary<EncodeHintType, object>
                {
                    { EncodeHintType.MARGIN, 0 }, // 边距
                    { EncodeHintType.CHARACTER_SET, "UTF-8" }, // 字符集
                    { EncodeHintType.ERROR_CORRECTION, ZXing.QrCode.Internal.ErrorCorrectionLevel.H } // 容错等级
                };
                
                // 使用ZXing库生成二维码
                var writer = new MultiFormatWriter();
                var bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
                
                // 转换为Bitmap
                return ToBitmap(bitMatrix);
            }
            catch (Exception ex)
            {
                throw new Exception(String.Format("生成二维码失败: {0}", ex.Message), ex);
            }
        }
        
        /// <summary>
        /// 将BitMatrix转换为Bitmap
        /// </summary>
        /// <param name="matrix">BitMatrix对象</param>
        /// <returns>Bitmap图片</returns>
        private static Bitmap ToBitmap(BitMatrix matrix)
        {
            int width = matrix.Width;
            int height = matrix.Height;
            var bitmap = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            
            for (int x = 0; x < width; x++)
            {
                for (int y = 0; y < height; y++)
                {
                    bitmap.SetPixel(x, y, matrix[x, y] ? Color.Black : Color.White);
                }
            }
            
            return bitmap;
        }
    }
}